package com.tg.app.activity.device.add;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.appbase.custom.constant.CommonConstants;
import com.base.BaseFragment;
import com.tange.base.toolkit.StringUtils;
import com.tange.feature.binding.query.DeviceBindingDirectly;
import com.tange.feature.data.structure.DeviceTypeBean;
import com.tange.module.core.wifi.scan.BizWiFiUtil;
import com.tange.module.socket.SocketIoConstants;
import com.tg.app.R;
import com.tg.app.activity.device.binding.DeviceTypeQuery;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.listener.OnAddDeviceListener;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.data.helper.DeviceTypeHelper;

public class DeviceProgressFragment extends BaseFragment{
    public static final String TAG = DeviceProgressFragment.class.getSimpleName();
    public static final String ARG_PARAM_UUID = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "param3";
    private static final int TOTAL_TIMES = 150000;
    private static final int INTERVAL_TIME = 1000;
    private static final String ARG_PARAM2_TYPE = "param_type";

    private String mUUID;
    private int doMatch = 0;
    private AddDeviceBroadCastReceiver receiver;
    private long deviceID;

    private ProgressBar mCustomCircleProgressBar;
    private CountDownTimer m4GTimer;
    private OnAddDeviceListener listener;
    private int mAuthStatus = 0;
    private String mICCId;


    private boolean loginStatusOutOfDate = false;

    private String mDeviceType;

    private DeviceTypeBean mDeviceTypeBean;
    public DeviceProgressFragment() {
    }

    public void setListener(OnAddDeviceListener listener) {
        this.listener = listener;
    }

    public static DeviceProgressFragment newInstance(String param1, int param2, int deviceType) {
        DeviceProgressFragment fragment = new DeviceProgressFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM_UUID, param1);
        args.putInt(ARG_PARAM2, param2);
        args.putInt(ARG_PARAM2_TYPE, deviceType);
        fragment.setArguments(args);
        return fragment;
    }

    public static DeviceProgressFragment newInstance(String param1, int param2, DeviceTypeBean deviceTypeBean) {
        DeviceProgressFragment fragment = new DeviceProgressFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM_UUID, param1);
        args.putInt(ARG_PARAM2, param2);
        args.putParcelable(ARG_PARAM3, deviceTypeBean);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mUUID = getArguments().getString(ARG_PARAM_UUID);
            mDeviceTypeBean = getArguments().getParcelable(ARG_PARAM3);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mActivity = getActivity();
        View view = inflater.inflate(R.layout.fragment_device_connect, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        TGLog.d("onActivityCreated");
        super.onActivityCreated(savedInstanceState);
        IntentFilter filter = new IntentFilter();
        filter.addAction(SocketIoConstants.NOTIFY_ADD_DEVICE);
        receiver = new AddDeviceBroadCastReceiver();
        mActivity.registerReceiver(receiver, filter);
        mCustomCircleProgressBar.setProgress(0);
        setToolbar();
        getDeviceType();
    }

    private void setToolbar() {
        ScanQrcodeActivity addFragmentTabActivity = (ScanQrcodeActivity) getActivity();
        if (addFragmentTabActivity != null) {
            addFragmentTabActivity.showRightOfToolbar(false);
            addFragmentTabActivity.setBackButtonTop(0);
            addFragmentTabActivity.getBackButton().setImageResource(R.drawable.ic_back_btn);
            addFragmentTabActivity.getBackButton().setOnClickListener(v -> {
                AddDeviceReportHelper.onEventClickByName(TAG, "back_left_btn");
                BizWiFiUtil.removeDeviceWifi();

                ActivityHelper.gotoDeviceListPage(getActivity());
            });
        }
    }

    private void onSuccessDeviceTypeQuery(DeviceTypeBean deviceTypeBean){
        mDeviceType =  deviceTypeBean.getDevice_type();
        BizWiFiUtil.saveNetworkWifi();

        TGLog.d("getDevice_type = " + mDeviceType);
        if (DeviceTypeHelper.is4GDevice(mDeviceType)){
            start4GTimer();
        }else{
            goToFailedActivity(ResourcesUtil.getString(R.string.scan_qrcode_uuid_error));
        }
    }

    private void getDeviceType(){
        if (mDeviceTypeBean != null){
            onSuccessDeviceTypeQuery(mDeviceTypeBean);
        }else{
            DeviceTypeQuery.create().request(mUUID, new DeviceTypeQuery.Callback() {
                @Override
                public void onSuccess(@NonNull DeviceTypeBean deviceTypeBean) {
                    boolean isShouldReset = deviceTypeBean.isShouldReset();
                    if (isShouldReset){
                        Intent intent = new Intent(getContext(), ResetErrorDeviceActivity.class);
                        intent.putExtra(DeviceTypeBean.DEVICE_TYPE_BEAN, deviceTypeBean);
                        ActivityHelper.jump2ResetDeviceActivity(getActivity(), mUUID, intent);
                    }else{
                        onSuccessDeviceTypeQuery(deviceTypeBean);
                    }
                }

                @Override
                public void onUuidNotFound() {
                    cancelTimer();
                    ActivityHelper.goToDisScanDeviceActivity(getActivity());
                }

                @Override
                public void onError(int errorCode, String errorMsg) {
                    start4GTimer();
                }
            });
        }

    }

    private void goToFailedActivity(String text){
        cancelTimer();
        TGToast.showToast(text);
        ActivityHelper.gotoAddFailedActivity(getActivity(), mDeviceType, mUUID, false);
    }


    private void start4GTimer() {
        doMatch = 0;
        m4GTimer = new CountDownTimer(TOTAL_TIMES, INTERVAL_TIME) {
            @SuppressLint("DefaultLocale")
            @Override
            public void onTick(long millisUntilFinished) {
                int process = (int)(TOTAL_TIMES - millisUntilFinished)/1000;
                if (process >  mCustomCircleProgressBar.getProgress()){
                    mCustomCircleProgressBar.setProgress(process);
                }

                TGLog.d("start4GTimer result.doMatch = " + doMatch);
                TGLog.d(TAG, "process = " + process + "millisUntilFinished = " + millisUntilFinished);
                if (doMatch % 10 == 0) {
                    bindDevice(false);
                }
                doMatch++;
            }

            @Override
            public void onFinish() {
                AddDeviceReportHelper.onEventLongTimeByName(TAG, "4g", 150000);
                finishTimer();
            }
        }.start();
    }


    private void finishTimer() {
        TGLog.d(TAG, "onFinish === ");
        mCustomCircleProgressBar.setProgress(TOTAL_TIMES);

        AddDeviceFailed(AddFragmentTabActivity.ERROR_NORMAL);
    }

    private void initView(View view) {
        mCustomCircleProgressBar = view.findViewById(R.id.loading_progress);
    }

    @Override
    public void onDetach() {
        TGLog.d("onDetach");
        super.onDetach();
        cancelTimer();

        if (receiver != null) {
            mActivity.unregisterReceiver(receiver);
        }
    }


    private void bindDevice(final boolean checkBindDevice) {
        if (loginStatusOutOfDate) {
            TGLog.i(TAG, "bindDevice: loginStatusOutOfDate , skip");
            return;
        }
        TGLog.i(TAG, "bindDevice: checkBindDevice = " + checkBindDevice);
        DeviceBindingDirectly.INSTANCE.require(mUUID, ResourcesUtil.getString(R.string.device_4g), ret -> {
            TGLog.i(TAG, "bindDevice: ret = " + ret);
            if (ret != null && ret.getSuccess()) {
                cancelTimer();
                if (listener != null) {
                    listener.onSet4GDeviceName(deviceID, mUUID, mAuthStatus, mICCId, 0);
                }
            } else if (ret != null){
                goToFailedActivity(ret.getMessage());
            }
        });
    }

    private void cancelTimer() {
        TGLog.d(ApDeviceListActivity.TAG, "cancelTimer");
        cancel4GTimer();
    }

    private void cancel4GTimer() {
        if (m4GTimer != null) {
            m4GTimer.cancel();
            m4GTimer = null;
        }
    }

    private void AddDeviceFailed(int errorSimNoneData) {
        cancelTimer();

        if (listener != null) {
            listener.onAddDeviceFailed(errorSimNoneData);
        }
    }

    private class AddDeviceBroadCastReceiver extends BroadcastReceiver {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!StringUtils.isEmpty(action) && action.equals(SocketIoConstants.NOTIFY_ADD_DEVICE)) {
                deviceID = intent.getLongExtra(CommonConstants.EXT_DEVICE_ID, 0);
                if (deviceID > 0) {
                    if (listener != null) {
                        listener.onSet4GDeviceName(deviceID, mUUID, mAuthStatus, mICCId, 0);
                    }
                }
            }
        }
    }
}
